<?php

namespace app\admin\controller\goods;

use app\common\controller\AdminController;
use app\common\service\RedisService;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="抢购商品")
 */
class Rush extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\GoodsRush();
        
    }

    /**
     * @NodeAnotation(title="列表")
     * TODO  参考 goods_rush.getGoods, 逻辑好像不符合原来程序,  @zzz  @zyy
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
           
            list($page, $limit, $where) = $this->buildTableParames();
// dump($where);die;
            foreach($where as $key =>&$val){
                if($val[0] == 'sche'){
                    $val[0] = 'b.name';
                }
                if($val[0] == 'view_code'){
                    $val[0] = 'code';
                }
                if($val[0] == 'name'){
                    $val[0] = 'a.name';
                }
                if($val[0] == 'state'){
                    $val[0] = 'a.state';
                }
            }
            // dump($where);die;
            $admin = session('admin');//
            $param = [];
            if(!empty($admin['uid'])){
                $param['a.bucket_id'] = $admin['uid'];
            }

            $count = $this->model
                ->alias('a')
                ->join("rush_schedule b","a.sid = b.id")
                ->where($where)
                ->where("a.state <> -1")
                ->where($param)
                ->count();
            $list = $this->model
                ->alias('a')
                ->join("rush_schedule b","a.sid = b.id")
                ->where($where)
                ->where("a.state <> -1")
                ->where($param)
                ->page($page, $limit)
                ->order($this->sort)
                ->field("a.*")
                ->select();

            //
            if(!empty($list)){
                foreach($list as &$val){
                    $val['view_code'] = $val['code'].$val['id'];
                    $val['category_name'] = Db::name("goods_category")->find($val['cid'])['name'];
                    $val['view_base_price'] = $val['base_price']/100;
                    $val['view_price'] = $val['price']/100;     
                    
                    if(!empty($val['rusher_id'])){
                        $rusher = Db::name("user")->find($val['rusher_id']);//抢购人
                        $val['rusher_name'] = $rusher ? $rusher['nickname'] : "";
                    } else {
                        $val['rusher_name'] = "--";
                    }
    
                    if(!empty($val['belong'])){
                        $belong = Db::name("user")->find($val['belong']);//所属人
                        $val['belong_name'] = $belong ? $belong['nickname'] : "";
                    } else {
                        $val['belong_name'] = "--";
                    }
    
                    if(!empty($val['rusher_id'])){
                        $payimg = Db::name("user_order_payimg")->where(['uid' => $val['rusher_id'],"order_id" => $val['current_order_id']])->find();//支付凭证
                        $val['payimg'] = $payimg ? $payimg['img'] : "";
                    } else {
                        $val['payimg'] = "";
                    }
                    
                    $bucket = Db::name("user_bucket")->find($val['bucket_id']);
                    $val['bucket'] = $belong ? $bucket['bucket_name'] : "";
                    
                    $sche = Db::name("rush_schedule")->find($val['sid']);
                    $val['sche'] = $sche ? $sche['name'] : "";

                    $val['img'] = implode("|",json_decode($val['img'],true));
                }
            }
            

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            
            return json($data);
        }
        return $this->fetch();
    }


     /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            unset($post['file']);
            $rule = [];
            $this->validate($post, $rule);
            try {
				
				//print_r($post); die;
                $post['img'] = json_encode(explode("|", $post['img']));
                //获取场次信息
                $schedule = Db::name("rush_schedule")->find($post['sid']);
                $post['bucket_id'] = $schedule['bucket_id'];
                $post['base_price'] = $post['base_price']*100;//金额为分
                $post['price'] = $post['price']*100;//金额为分

                // 分仓添加商品, 初始属于自己
                $post['belong'] = $post['bucket_id'];

                //保存数据
                //$save = $this->model->save($post);
                $good_id = $this->model->insertGetId($post);
                //修改商品和抢购场次关系表
                if(Db::name("goods_rush_schedule_map")->where(['gid' => $good_id])->find()){
                    //更新
                    Db::name("goods_rush_schedule_map")->where(['gid' => $good_id])->update(['sid' => $post['sid']]);
                } else {
                    //新增
                    Db::name("goods_rush_schedule_map")->insert(['sid' => $post['sid'],'gid' => $good_id]);
                }
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }

            // 添加完成同步一次  syncRushSingle     $good_id = $this->model->insertGetId($post);
            $good_id ? self::sync_one($good_id) : false;
            // 更新抢购场次:  TODO  手动

            $good_id ? $this->success('保存成功, 推送场次请手动 !') : $this->error('保存失败');
        }
        // 当前账号分仓id, 也是userid
        $admin = session('admin'); //->where(['b.admin_uid' => $admin['uid'] ])
        //商品分类
        $category = Db::name("goods_category")->where(['state' => 1])->select();
        //抢购场次
        $schedule = Db::name("rush_schedule")
        ->alias('a')
        ->join("user_bucket b","a.bucket_id = b.id")
        //->where(['a.state' => 1])
        ->where(['b.admin_uid' => $admin['uid'] ])
        ->field("a.id,a.name,b.bucket_name")
        ->select();

        $this->assign("schedule", $schedule);
        $this->assign("category", $category);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);
        
        
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            try {
                $post['img'] = json_encode(explode("|", $post['img']));
                
                //获取场次信息
                $schedule = Db::name("rush_schedule")->find($post['sid']);
                $post['bucket_id'] = $schedule['bucket_id'];
                $post['base_price'] = $post['base_price']*100;//金额为分
                $post['price'] = $post['price']*100;//金额为分
                if($post['state'] == 1){
                    //修改商品状态为已上架，修改抢购人的id为0
                    $post['rusher_id'] = 0;
                    //修改订单状态为-1
                    Db::name("user_order")->where(['id' => $row['current_order_id']])->update(['state' => "-1"]);
                }

                $save = $row->save($post);
                $good_id = $row['id'];
                //修改商品和抢购场次关系表
                if(Db::name("goods_rush_schedule_map")->where(['gid' => $good_id])->find()){
                    //更新
                    Db::name("goods_rush_schedule_map")->where(['gid' => $good_id])->update(['sid' => $post['sid']]);
                } else {
                    //新增
                    Db::name("goods_rush_schedule_map")->insert(['sid' => $post['sid'],'gid' => $good_id]);
                }
            } catch (\Exception $e) {
                $this->error('保存失败');
            }

            // 添加完成同步一次  syncRushSingle
            $good_id ? self::sync_one($good_id) : false;
            // 更新抢购场次:  TODO  手动

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        // 当前账号分仓id, 也是userid
        $admin = session('admin'); //->where(['b.admin_uid' => $admin['uid'] ])

        //商品分类
        $category = Db::name("goods_category")->where(['state' => 1])->select();
        //抢购场次
        $schedule = Db::name("rush_schedule")
        ->alias('a')
        ->join("user_bucket b","a.bucket_id = b.id")
        // ->where(['a.state' => 1])   //  wtt修改:  场次暂停状态也可以选
        ->where(['b.admin_uid' => $admin['uid'] ])
        ->field("a.id,a.name,b.bucket_name")
        ->select();

        //所属人
        $belong = Db::name("user")->where(['bucket_id' => $admin['uid']])->select();
        $this->assign("belong", $belong);

        //显示图片数据修改
        $row['img'] = implode("|",json_decode($row['img'],true));
        $row['base_price'] = $row['base_price']/100;
        $row['price'] = $row['price']/100;

        $this->assign("schedule", $schedule);
        $this->assign("category", $category);
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    //批量修改真实价格
    public function tiaojia(){
        
        $id = $this->request->get("id");
        
        if ($this->request->isPost()) {
            $post = $this->request->post();
            $rule = [];
            $this->validate($post, $rule);
            
            try {
                $arr_ids = explode(",",$post['rid']);
                
                foreach($arr_ids as $val){
                    //商品信息
                    $rush = $this->model->find($val);
                    //更新商品信息
                    $price = $rush['price'] + ($rush['price'] * $post['jiage']/100);
                    $save = $this->model->where(['id' => $val])->update(['price' => $price]);
                }
                
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign("id", $id);
        return $this->fetch();

    }
    

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete($id)
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->update(['id' => $id, "state" => -1]);
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="批量上架")
     */
    public function shangjia()
    {
        $id = $this->request->param('id');
        //dump($id);die;
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->update(['id' => $id, "state" => 1]);
        } catch (\Exception $e) {
            $this->error('上架失败');
        }
        $save ? $this->success('上架成功') : $this->error('上架失败');
    }

   
    /**
     * @NodeAnotation(title="拆分商品")
     */
    public function split($id)
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            try {
                // 拆分商品提交后操作   TODO   参: goods_rush.divRushGoods

                // 待拆分商品
                $originData = $this->model->find($id) ;
                $toData = $this->model->find($post['gid'] ) ;
//print_r($toData);die;
                $price1 = $originData->price - $toData->base_price ;

                // 待写入更新的价格:  -- 被拆商品
                $originData->price = $price1 ;
                
                $updateOrigin = $originData->save();

                // 待写入更新的价格: -- 新商品
                $toData->price = $toData->base_price ;
                $toData->belong = $originData->belong ;
                $toData->state = $originData->state ;
                $toData->bucket_id = $originData->bucket_id ;
                $toData->sid = $originData->sid ;
                $updateTo = $toData->save();

        //  // 原始逻辑~~~~   TODO    @重要
        //    // 检查是否在抢购中,在抢购中不允许拆分? 暂不检查，下周期更新
        //    // 旧的拆分逻辑
        //    // await mysql.query("UPDATE goods_rush SET price=? WHERE gid=?", [new_price, origin_gid]);
        //    // let s = await mysql.query("UPDATE goods_rush SET belong=?,state=? WHERE gid IN (?)", [originData.belong, originData.state, sub_gids]);
        //
        //    // 新拆分逻辑，订单的收益也要分开计算
        //    let publishOrder = await mysql.query("SELECT * FROM user_order_publish WHERE order_no=?", [originData.publish_order_no]);
        //    publishOrder = publishOrder[0];
        //    let divRate = new_price / originData.price;
        //    await mysql.query("UPDATE goods_rush SET price=? WHERE gid=?", [new_price, origin_gid]);
        //    await mysql.query("UPDATE user_order_publish SET newprice=?,oldprice=?,payprice=? WHERE id=?", [new_price, parseInt(publishOrder.oldprice * divRate), parseInt(publishOrder.payprice * divRate), publishOrder.id]);
        //
        //    for (let i = 0; i < sql_result.length; i++) {
        //                    let oprice = parseInt(sql_result[i].price / publishOrder.newprice * publishOrder.oldprice); // 按比例折算收益订单原价格
        //        let pprice = parseInt(oprice * publishOrder.rate * 0.01); // 按比例折算收益订单新价格
        //        let divPublish = await web_order.createPublishOrderDiv(publishOrder.uid, sql_result[i].gid, sql_result[i].price, oprice, pprice, publishOrder.rate, publishOrder.coupon_id, publishOrder.relate_order_id);
        //        let s = await mysql.query("UPDATE goods_rush SET belong=?,state=?,publish_order_no=? WHERE gid =?", [originData.belong, originData.state, divPublish.order_no, sql_result[i].gid]);
        //    }
//
//                await goods_rush.syncRush();

                $save = $updateOrigin ;
                //$save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }

            // 拆分后自动同步
            $save ? self::sync() : false;

            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        

        $admin = session('admin');
        $param = [];
        // if(!empty($admin['uid'])){
        //     $param['bucket_id'] = $admin['uid'];
        // }

        //获取未上架的商品
        // 原逻辑:   SELECT * FROM goods_rush WHERE state=0 AND belong IN (?) AND last_belong=0
        //$off_goods = $this->model->where(['state' => 0,"rusher_id" => 0,"belong" => 0])->where($param)->select();
        $off_goods = $this->model->where(['state' => 0,"last_belong" => 0, "belong" => $admin['uid'] ])->where($param)->select();

        //获取商品信息
        $goods = $this->model->find($id);

        $this->assign("goods", $goods);
        $this->assign("off_goods", $off_goods);

        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="推送v2")
     * @version 1.0
     */
    public function sync()
    {
        $admin = session('admin');
        $uid = $admin['uid'] ;
            //推送抢购商品  $this->model->fetchSql    limit for test
        $list = Db::query("SELECT a.*,c.nickname belong_nickname,c.avatar belong_avatar 
                     FROM sy_goods_rush a 
                     LEFT JOIN sy_user c ON c.id=a.belong 
                     WHERE a.state IN (0,1,2,3,4,5) AND a.bucket_id = '{$uid}'
                     ORDER BY a.sid ASC,a.id ASC");
        $data = collection($list)->toArray();

        // 清除抢购列表键
        $delKeys = RedisService::select(0)->keys(self::KEYS['RUSH_GOODS'].'*');
        if ($delKeys) {
            RedisService::select(0)->del($delKeys);
        }
        // 添加商品至抢购列表
        for ($i = 0; $i < count($data); $i++) {
            RedisService::select(0)->hset(self::KEYS['RUSH_GOODS']. $data[$i]['sid'], $data[$i]['id'].'' , json_encode($data[$i], JSON_UNESCAPED_UNICODE ));
        }
        // 清除计数器
        $delKeys1 = RedisService::select(0)->keys(self::KEYS['RUSH_GOODS_COUNTER'].'*');
        if ($delKeys1) {
            RedisService::select(0)->del($delKeys1);
        }
        // 添加计数器
        for ( $i = 0; $i < count($data); $i++) {
            $count = 0;
            if ($data[$i]['state'] == 1) {
                $count = 1;
            }
            $map[ $data[$i]['id'] ] = $count;
            RedisService::select(0)->hmset( self::KEYS['RUSH_GOODS_COUNTER'].$data[$i]['sid'] , $map );
        }
        $this->success("操作成功");
    }



    /**
     * @NodeAnotation(title="推送单个v2")
     * @version 1.0
     */
    public function sync_one($gid)
    {
        // TODO 入参:商品id  @zyy
        // TODO 添加抢购商品成功时, 修改抢购商品成功时 调用
        // $gid = 1402893 ;
        // #同步抢购
        $data = Db::query("SELECT * FROM sy_goods_rush WHERE id=?", [$gid]);
//print_r($data); die;
        if($data){
            RedisService::select(0)->hSet( self::KEYS['RUSH_GOODS']. $data[0]['sid'], $gid.'' , json_encode($data[0], JSON_UNESCAPED_UNICODE) );

            if ($data[0]['state'] == 1) {
                RedisService::select(0)->HSET( self::KEYS['RUSH_GOODS_COUNTER'].$data[0]['sid'] , $gid.'', '1');
            } else {
                RedisService::select(0)->HSET( self::KEYS['RUSH_GOODS_COUNTER'].$data[0]['sid'] , $gid.'', '0');
            }
        }

    }


    /**
     * @NodeAnotation(title="导出v2")
     */
    public function daochu()
    {
        // TODO  参考原程序逻辑
    }

    /**
     * @NodeAnotation(title="修改分仓v2")
     */
    public function change_bucket()
    {
        // TODO  参考原程序逻辑
//        let token_info = await base.checkAdminToken(req);
//      if (token_info.res_code < 0 || token_info.data.roles.indexOf(1) == -1) {
//          res.send(base.result_error("登录失败"));
//          return;
//      }
//      let user_info = token_info.data;
//
//      let gid = parseInt(req.body.gid);
//      if (!(gid > 0)) {
//          res.send(base.result_error("抢购商品id错误"));
//          return;
//      }
//
//      let bucket_id = parseInt(req.body.bucket_id);
//      if(bucket_id < 0){
//          res.send(base.result_error("参数错误"));
//          return;
//      }
//
//      let sql = `UPDATE goods_rush SET bucket_id=? WHERE gid=?`;
//      let sql_params = [bucket_id, gid];
//      let sql_result = await mysql.query(sql, sql_params);
//      if (sql_result.affectedRows > 0) {
//          res.send(base.result_ok("修改成功"));
//          return;
//      } else {
//          res.send(base.result_warning("修改异常"));
//          return;
//      }

    }

    /**
     * @NodeAnotation(title="拆分商品v2")
     */
    public function divgoods()
    {
        // TODO  参考原程序逻辑
//        let user_info = token_info.data;
//
//        let origin_gid = parseInt(req.body.origin_gid);
//        if (!(origin_gid > 0)) {
//            res.send(base.result_error("待拆分商品id错误"));
//            return;
//        }
//
//        let new_price = parseInt(req.body.new_price + 0.1);
//        if (!(new_price > 0)) {
//            res.send(base.result_error("待拆分商品价格错误"));
//            return;
//        }
//
//        let sub_gids = req.body.sub_gids;
//        if (!Array.isArray(sub_gids) || sub_gids.length == 0) {
//            res.send(base.result_error("新拆分商品id错误"));
//            return;
//        }
//
//        let sql = `SELECT * FROM goods_rush WHERE gid=? AND state=1`;
//        let sql_params = [origin_gid];
//        let sql_result = await mysql.query(sql, sql_params);
//        if (sql_result.length == 0) {
//            res.send(base.result_error("没有找到待拆分的商品"));
//            return;
//        }
//        let originData = sql_result[0];
//
//        sql = `SELECT * FROM goods_rush WHERE gid IN (?) AND last_belong=0`;
//        sql_result = await mysql.query(sql, [sub_gids]);
//        if (sql_result.length != sub_gids.length) {
//            res.send(base.result_error("(部分)新拆分商品没有找到"));
//            return;
//        }
//        let sub_total_price = 0;
//        sql_result.forEach(item => {
//            sub_total_price += item.price;
//        });
//
//        if ((new_price + sub_total_price) != originData.price) {
//            console.log('拆分价格错误');
//            console.log(`新价:${new_price} 子商品总价:${sub_total_price} 原价:${originData.price}`);
//            console.log(`原商品:${origin_gid} 子商品:${sub_gids}`);
//            res.send(base.result_error("拆分失败"));
//            return;
//        }
//
//
//        // 新拆分逻辑，订单的收益也要分开计算
//        let publishOrder = await mysql.query("SELECT * FROM user_order_publish WHERE order_no=?", [originData.publish_order_no]);
//        publishOrder = publishOrder[0];
//        let divRate = new_price / originData.price;
//        await mysql.query("UPDATE goods_rush SET price=? WHERE gid=?", [new_price, origin_gid]);
//        await mysql.query("UPDATE user_order_publish SET newprice=?,oldprice=?,payprice=? WHERE id=?", [new_price, parseInt(publishOrder.oldprice * divRate), parseInt(publishOrder.payprice * divRate), publishOrder.id]);
//
//        for (let i = 0; i < sql_result.length; i++) {
//            let oprice = parseInt(sql_result[i].price / publishOrder.newprice * publishOrder.oldprice); // 按比例折算收益订单原价格
//            let pprice = parseInt(oprice * publishOrder.rate * 0.01); // 按比例折算收益订单新价格
//            let divPublish = await web_order.createPublishOrderDiv(publishOrder.uid, sql_result[i].gid, sql_result[i].price, oprice, pprice, publishOrder.rate, publishOrder.coupon_id, publishOrder.relate_order_id);
//            let s = await mysql.query("UPDATE goods_rush SET belong=?,state=?,publish_order_no=? WHERE gid =?", [originData.belong, originData.state, divPublish.order_no, sql_result[i].gid]);
//        }
//
//        await goods_rush.syncRush();
//        res.send(base.result_ok("拆分成功"));
//        return;

    }

    /**
     * @NodeAnotation(title="获取可拆分商品v1")
     */
    public function candivgoods()
    {
//        let token_info = await base.checkAdminToken(req);
//    if (token_info.res_code < 0 || token_info.data.roles.indexOf(1) == -1) {
//        res.send(base.result_error("登录失败"));
//        return;
//    }
//    let user_info = token_info.data;
//
//    let admins = await mysql.query("SELECT * FROM user WHERE roles LIKE '%1%' AND state=1");
//    if (admins.length > 0) {
//        admins = admins.map(item => {
//            return item.uid;
//        });
//    } else {
//        admins = [user_info.uid];
//    }
//
//    let sql = `SELECT * FROM goods_rush WHERE state=0 AND belong IN (?) AND last_belong=0`;
//    let sql_result = await mysql.query(sql, [admins]);
//    res.send(base.result_ok("ok", sql_result));
    }
    /**
     * @NodeAnotation(title="上帝模式-推送抢购商品v2")
     */
    public function godsync(){
    //        let token_info = await base.checkAdminToken(req);
    //    if (token_info.res_code < 0 || token_info.data.roles.indexOf(1) == -1) {
    //        res.send(base.result_error("登录失败"));
    //        return;
    //    }
    //    let user_info = token_info.data;
    //
    //    let sql = `SELECT a.*,c.nickname belong_nickname,c.avatar belong_avatar
    //     FROM goods_rush a
    //     LEFT JOIN user c ON c.uid=a.belong
    //     WHERE a.state IN (0,1,2,3,4,5)
    //     ORDER BY a.sid ASC,a.gid ASC`;
    //    let data = await mysql.query(sql, []);
    //
    //    // 清除抢购列表键
    //    let delKeys = await redis.Client0.keys(`${KEYS.RUSH_GOODS}*`);
    //    if (delKeys.length > 0) {
    //        await redis.Client0.del(delKeys);
    //    }
    //    // 添加商品至抢购列表
    //    for (let i = 0; i < data.length; i++) {
    //            await redis.Client0.hSet(`${KEYS.RUSH_GOODS}${data[i].sid}`, data[i].gid.toString(), JSON.stringify(data[i]));
    //    }
    //
    //    // 清除计数器
    //    delKeys = await redis.Client0.keys(`${KEYS.RUSH_GOODS_COUNTER}*`);
    //    if (delKeys.length > 0) {
    //        await redis.Client0.del(delKeys);
    //    }
    //    // 添加计数器
    //    for (let i = 0; i < data.length; i++) {
    //            let map = new Map();
    //        let count = 0;
    //        if (data[i].state == 1) {
    //            count = 1;
    //        }
    //        map.set(`${data[i].gid}`, parseInt(count));
    //        await redis.Client0.HSET(`${KEYS.RUSH_GOODS_COUNTER}${data[i].sid}`, map);
    //    }
    //
    //    res.send(base.result_ok('ok'));
    }

}